package com.xhsj.user.lsm.service;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xhsj.user.event.event.MessageEvent;
import com.xhsj.user.hr.process.hrLeaveProcess.mapper.TbHrApprovalLeaveApplyMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.lsm.common.Constant;
import com.xhsj.user.lsm.model.MyBadgesUseApplyModel;
import com.xhsj.user.lsm.model.TaskModel;
import com.xhsj.user.sms.base.BaseService;
import com.xhsj.user.lsm.entity.TbBadgesUseApply;
import com.xhsj.user.lsm.entity.TbBadgesUseApplyFile;
import com.xhsj.user.lsm.entity.TbContractApply;
import com.xhsj.user.lsm.mapper.TbBadgesUseApplyMapper;
import com.xhsj.user.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 证章使用申请 服务实现类
 * </p>
 *
 * @author suxiaolin
 * @since 2020-03-16
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class TbBadgesUseApplyService extends BaseService<TbBadgesUseApplyMapper, TbBadgesUseApply>{
    @Autowired
    private TbBadgesUseApplyMapper dao;

    @Autowired
    private TbBadgesProcessTaskService tbBadgesProcessTaskService;

    @Autowired
    private TbBadgesProcessHiTaskService tbBadgesProcessHiTaskService;

    @Autowired
    private TbContractApplyService tbContractApplyService;

    @Autowired
    private TbBadgesUseApplyFileService tbBadgesUseApplyFileService;

    @Autowired
    private TbGlobalUserService tbGlobalUserService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private TbHrApprovalLeaveApplyMapper tbHrApprovalLeaveApplyMapper;
    //角色名称 综合管理部
    @Value("${rolekeyname.integratedManager}")
    private String integratedManager;



    public boolean startProcess(TbBadgesUseApply entity) throws Exception {

        try {
            List<String> types = entity.getTypes();
            entity.setType(String.join(",",types));
            List<String> badgesManagerIds = entity.getBadgesManagerIds();
            entity.setBadgesManagerId(String.join(",",badgesManagerIds));
            boolean save = super.save(entity);

            List<TbBadgesUseApplyFile> useApplyFileLists = entity.getUseApplyFileLists();
            if (useApplyFileLists !=null && useApplyFileLists.size() >0) {
                for (TbBadgesUseApplyFile useApplyFileList : useApplyFileLists) {
                    if (StringUtils.isBlank(useApplyFileList.getId())) {
                        useApplyFileList.setId(IdGen.uuid());
                    }
                    useApplyFileList.setUseApplyId(entity.getId());
                }
                boolean b = tbBadgesUseApplyFileService.saveOrUpdateBatch(useApplyFileLists);
                if (!b) {
                    log.error("保存文件错处");
                    throw new Exception("保存文件错处");
                }
            }
            // 查询领导
            String leader = String.valueOf(tbGlobalUserService.getLeaderId(StringUtils.toLong(StringUtils.toLong(entity.getCreateBy()))));
//            String leader = tbGlobalUserService.getLeaderByUserId(StringUtils.toLong(entity.getCreateBy()));
            if (StringUtils.isBlank(leader) || leader == "null") {
                throw new Exception("部门领导不存在,请联系管理员添加相关人员");
            }
            Map<String, Object> map = Maps.newHashMap();
            map.put("createBy",entity.getCreateBy());
            map.put("dataId",entity.getId());
            map.put("type",1);
            if ("291".equals(leader) ){
                //根据角色名查找角色
                List<String>  roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(integratedManager);
                if (roleListByRoleName ==null || roleListByRoleName.size() == 0) {
                    throw new Exception("下一节点审核角色不存在,请联系管理员添加相关人员");
                }
                // 检查角色下是否有用户
                tbGlobalUserService.checkRoleUserId(integratedManager,"综合管理部负责人");
                map.put("roleIds",roleListByRoleName);
            }else {
                map.put("userId",leader);
            }

            String s = tbBadgesProcessTaskService.startProcess(map);
            if (!save){
                log.error("保存证章使用申请返回值为false");
                throw new Exception("保存证章使用申请返回值为false");
            }
           //申请表的节点状态
            entity.setNodeName(s);
            boolean b = this.updateById(entity);
            if (!b) {
                log.error("修改证章申请节点名称失败");
                throw new Exception("修改证章申请节点名称失败");
            }

            if(StringUtils.isNotBlank(map.get("userId"))) {
                map.put("userId", Arrays.asList(String.valueOf(map.get("userId")).split(",")));
            }
            sendMessage(map,entity.getId());

        } catch (Exception e) {
            log.error("保存证章使用申请出错,{}",e);
            throw e;
        }
        return true;
    }

    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbBadgesUseApply getById(Serializable id) {
        TbBadgesUseApply tbBadgesUseApply = super.getById(id);
        QueryWrapper<TbBadgesUseApplyFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("use_apply_id",id);
        List<TbBadgesUseApplyFile> list = tbBadgesUseApplyFileService.list(queryWrapper);
        tbBadgesUseApply.setUseApplyFileLists(list);
        return tbBadgesUseApply;
    }

    @Override
    //@CacheEvict(cacheNames="TbBadgesUseApply", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

    //@Cacheable(key = "#data",sync = true)
    public IPage<MyBadgesUseApplyModel> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }
        Page<MyBadgesUseApplyModel> page = new Page(currentPage,pageSize);
        IPage<MyBadgesUseApplyModel> listPage = dao.myBadgesUseApplyList(page, String.valueOf(data.get("userId")));
        return listPage;
    }

    @Override
    //@Cacheable(value = "TbBadgesUseApply",sync = true)
    public List<TbBadgesUseApply> selectAll() {
        return super.selectAll();
    }


    public boolean execProcess(Map<String, Object> data) throws Exception {
        try {
            Integer status = StringUtils.toInteger(data.get("status"));// 对应节点表
            if (status == 1) {
                // 检查用户是否存在
                tbGlobalUserService.checkUserId(data.get("proposerId"));
            }
            data.put("type",1);
            String s = tbBadgesProcessTaskService.handleAudit(data);
            // 数据id
            String dataId = String.valueOf(data.get("dataId"));
            Integer significanceIdentify = null;
            if(StringUtils.isNotBlank(data.get("significanceIdentify"))) {
                significanceIdentify = StringUtils.toInteger(data.get("significanceIdentify"));
            }

            TbBadgesUseApply tbBadgesUseApply = new TbBadgesUseApply();
            tbBadgesUseApply.setId(dataId);
            tbBadgesUseApply.setNodeName(s);
            tbBadgesUseApply.setSignificanceIdentify(significanceIdentify);
            boolean b = this.updateById(tbBadgesUseApply);
            if (!b) {
                log.error("修改证章申请节点名称失败");
                throw new Exception("修改证章申请节点名称失败");
            }
            sendMessage(data, dataId);


        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        return true;
    }

    private void sendMessage(Map<String, Object> data, String dataId) {

        String fullName = dao.getFullNameByDataId(dataId);
        // 流程申请用户id
        String proposerId = String.valueOf(data.get("proposerId"));
        // 状态
        Integer status = StringUtils.toInteger(data.get("status"));// 对应节点表

        // 登录用户id
        String createBy = String.valueOf(data.get("createBy"));
        // 下一个节点审核用户id
        Object userId =  data.get("userId");
        // 下一个节点审核用户角色
        Object roleIds = data.get("roleIds");

        // 节点id
        String nodeId = String.valueOf(data.get("nodeId"));

        List<Long> userIds = Lists.newArrayList();
        if (!Objects.isNull(userId)) {
            List<String> userIdList = JSONArray.parseArray(String.valueOf(userId), String.class);
            for (String u : userIdList) {
                userIds.add(Long.valueOf(u));
            }
        }
        if (!Objects.isNull(roleIds)) {
            List<String> role_Ids = JSONArray.parseArray(String.valueOf(roleIds), String.class);
            List<Long> collectRoleIds = role_Ids.stream().map(Long::parseLong).collect(Collectors.toList());
            List<Long> userListByRoleIds = tbGlobalUserService.getUserListByRoleIds(collectRoleIds);
            userIds.addAll(userListByRoleIds);
        }

        // 消息发送
        Map<String, Object> messageMap = Maps.newHashMap();
        messageMap.put("projectId",2);
        messageMap.put("dataId",dataId);
        messageMap.put("title", MessageConstant.MSG_12);
        messageMap.put("name", fullName);
        messageMap.put("sender",proposerId);
        messageMap.put("examineStatus",1);
        messageMap.put("userIds",userIds);


        if (status == 1) { // 审核退回
            userIds.add(Long.valueOf(proposerId));
//            messageMap.put("title", Constant.messageMap.get(nodeId));
            messageMap.put("title", MessageConstant.MSG_12);
            messageMap.put("examineStatus",2);
            messageMap.put("sender",createBy);
            messageMap.put("userIds",userIds);

        }

        applicationContext.publishEvent(new MessageEvent(this,messageMap));
    }

    public IPage<Map<String,Object>> findHiTaskList(Map<String, Object> data) {

        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }
        int type = 0;
        if (!Objects.isNull(data.get("type"))) {
            type = StringUtils.toInteger(data.get("type"));
        }

        String name = StringUtils.getStringValue(data, "name");
        String proposerName = StringUtils.getStringValue(data, "proposerName");
        String userId =String.valueOf(StringUtils.getIntegerValue(data, "userId"));
        Integer status = StringUtils.getIntegerValue(data, "status");

        String applyReason = Objects.isNull(data.get("applyReason"))?"": String.valueOf(data.get("applyReason"));
        //获取当前用户的角色
        List<String> roleList = tbGlobalUserService.getRoleListByUserId(StringUtils.toInteger(userId));

        IPage<TaskModel> page = new Page(currentPage, pageSize);

        if (type == 2) {
            Object contractNo = data.get("contractNo");

            Object partiesName = data.get("partiesName");

            IPage<Map<String,Object>> iPage = dao.findContractHiTaskList(page,userId,status,roleList,type,contractNo,partiesName);
            return iPage;
        }

        IPage<Map<String,Object>> iPage = dao.findHiTaskList(page,userId,name,applyReason,proposerName);
        for (Map<String, Object> record : iPage.getRecords()) {
            String type1 = String.valueOf(record.get("type"));

            List<String> list = Arrays.asList(type1.split(","));
            record.put("types",list);
        }

        return iPage;
    }

    public IPage<Map<String, Object>> findRunTaskList(Map<String, Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        int type = 1;
        if (!Objects.isNull(data.get("type"))) {
            type = StringUtils.toInteger(data.get("type"));
        }
        String userId = String.valueOf(data.get("userId"));
        String applyReason = Objects.isNull(data.get("applyReason"))?"": String.valueOf(data.get("applyReason"));

        List<String> roleList = tbGlobalUserService.getRoleListByUserId(Long.parseLong(userId));

        Page<TaskModel> page = new Page(currentPage,pageSize);
        if (type == 2) { // 查询合同审核数据
            Object contractNo = data.get("contractNo");

            Object partiesName = data.get("partiesName");

            IPage<Map<String, Object>> iPage = dao.findContractRunTaskList(page,userId,roleList, applyReason,contractNo,partiesName);
            return iPage;
        }

        IPage<Map<String, Object>> iPage = dao.findRunTaskList(page,userId,roleList, applyReason);
        for (Map<String, Object> record : iPage.getRecords()) {
            String type1 = String.valueOf(record.get("type"));
            List<String> list = Arrays.asList(type1.split(","));
            record.put("types",list);

            QueryWrapper<TbBadgesUseApplyFile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("use_apply_id",record.get("dataId"));
            List<TbBadgesUseApplyFile> list1 = tbBadgesUseApplyFileService.list(queryWrapper);
            record.put("useApplyFileLists",list1);

        }
        return iPage;
    }

    public IPage<Map<String,Object>> findUserRecord(Map<String,Object> data) {

        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        Page<Object> page = new Page(currentPage,pageSize);
        Object id = data.get("id");
        return dao.findUserRecord(page,String.valueOf(id),"完结");
    }

    public boolean cancle(String id) throws Exception {

        try {
            Map<String, Object> columnMap = Maps.newHashMap();
            columnMap.put("data_id",id);
            boolean b = tbBadgesProcessTaskService.delByDataId(id);
            boolean b1 = tbBadgesProcessHiTaskService.delByDataId(id);
            boolean b2 = this.delById(id);
            if (b && b1 && b2) {
                return true;
            }else{
                throw new Exception("删除数据异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("删除数据异常",e);
        }
    }

    private boolean delById(String id) {
        Integer result = dao.delById(id);
        return null != result && result >= 0;
    }

    public IPage<Map<String,Object>> getUseList(Map<String, Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        Page<TbBadgesUseApply> page = new Page(currentPage,pageSize);


        String name = "";
        if (!Objects.isNull(data.get("name"))) {
            name =data.get("name").toString();
        }

        String applyReason = "";
        if (!Objects.isNull(data.get("applyReason"))) {
            applyReason = data.get("applyReason").toString();
        }
        Integer acType = 0;
        if (!Objects.isNull(data.get("acType"))) {
            acType = StringUtils.toInteger(data.get("acType"));
        }
        List<String> list = Lists.newArrayList();
        list.add("填写文件登记表");
        list.add("使用中");
        list.add("完结");

        IPage<Map<String,Object>> iPage = dao.getUseList(page,name,applyReason,acType,list);
        return iPage;



    }

    // 证章合同代办数
    public Integer badgesOrContractAgencyNum(Integer userId,Integer type) {
        List<String> roleList = tbGlobalUserService.getRoleListByUserId(userId);
        if(type==1){
            return dao.badgesAgencyNum(userId,roleList,type);
        }
        if(type==2){
            return dao.contractAgencyNum(userId,roleList,type);
        }
        return  0;
    }

    public IPage<Object> findApplyList(Map<String, Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        String type = String.valueOf(data.get("type")); // 1 使用申请 2 合同申请
        String userId = String.valueOf(data.get("userId"));
        if ("1".equals(type)) {// 使用申请
            IPage<TbBadgesUseApply> page = new Page(currentPage,pageSize);
            IPage<Object> selectPage = dao.findBadgesList(page,userId);
            for (Object object : selectPage.getRecords()) {
                TbBadgesUseApply record = (TbBadgesUseApply) object;
                String type1 = record.getType();
                if (StringUtils.isNotBlank(type1)) {
                    List<String> list = Arrays.asList(type1.split(","));
                    record.setTypes(list);
                }
                Map<String,String> map = dao.getTransferByDataId(record.getId());
                if (map !=null) {
                    List<Object> list = Lists.newArrayList();
                    list.add(map.get("dept_id"));
                    list.add(map.get("user_id"));
                    record.setUserList(list);
                    record.setTransferId(map.get("id"));
                }else{
                    List<Object> list = Lists.newArrayList();
                    record.setUserList(list);
                    record.setTransferId("");
                }
            }
            return selectPage;
        }else{
            IPage<TbContractApply> page = new Page(currentPage,pageSize);
            IPage<Object> selectPage = tbContractApplyService.findContractApplyList(page,userId);
            for (Object record1 : selectPage.getRecords()) {
                TbContractApply record = (TbContractApply) record1;
                Map<String,String> map = dao.getTransferByDataId(record.getId());
                if (map !=null) {
                    List<Object> list = Lists.newArrayList();
                    list.add(map.get("dept_id"));
                    list.add(map.get("user_id"));
                    record.setUserList(list);
                    record.setTransferId(map.get("id"));
                }else{
                    List<Object> list = Lists.newArrayList();
                    record.setUserList(list);
                    record.setTransferId("");
                }
            }
            return selectPage;
        }
    }

    /**
     * @Description: 部门用章统计
     * @Param:  date-日期
     * @Author: liuqinghua
     * @Date: 2021/9/6
     */
    public List<Map<String,Integer>> getBadgesStatistics(String date) {
        String now = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        boolean isNow = false;
        if(now.equals(date))
            isNow = true;
        List<Map<String, Integer>> badgesStatistics = dao.getBadgesStatistics(date, isNow);
        List<Map<String, Integer>> collect = badgesStatistics.stream().
                sorted(Comparator.comparing(this::getMapValue).reversed())
                .collect(Collectors.toList());

        return collect;
    }

    public Integer getMapValue(Map<String,Integer> map) {
      return Integer.valueOf(String.valueOf(map.get("value")));
    }

}
